﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using JY.Common.WcfHost.Configurations;

namespace JY.Common.WcfHost
{
    /// <summary>
    /// 服务启动器
    /// </summary>
    public class ServiceLauncherBase
    {
        #region # 变量
        #region WCF服务Hosts——List<ServiceHost> ServiceHosts
        /// <summary>
        /// WCF服务Hosts
        /// </summary>
        protected readonly List<ServiceHost> ServiceHosts;
        #endregion
        #endregion

        #region # 构造器
        /// <summary>
        /// 构造器
        /// </summary>
        public ServiceLauncherBase()
        {
            Assembly currentAssembly = Assembly.Load(WcfHostSection.Section.WcfImplementAssembly.Value);
            IEnumerable<Type> types = currentAssembly.GetTypes().Where(x => !x.IsAbstract && !x.IsInterface);
            this.ServiceHosts = new List<ServiceHost>();
            foreach (var type in types)
            {
                this.ServiceHosts.Add(new ServiceHost(type));
            }
        }
        /// <summary>
        /// 构造器
        /// </summary>
        public ServiceLauncherBase(string wcfImplementAssembly)
        {
            Assembly currentAssembly = Assembly.Load(wcfImplementAssembly);
            IEnumerable<Type> types = currentAssembly.GetTypes().Where(x => !x.IsAbstract && !x.IsInterface);
            this.ServiceHosts = new List<ServiceHost>();
            foreach (var type in types)
            {
                this.ServiceHosts.Add(new ServiceHost(type));
            }
        }
        #endregion

        #region # 方法
        #region # 启动服务——void Start()
        /// <summary>
        /// 启动服务
        /// </summary>
        public virtual void Start()
        {
            foreach (var serviceHost in this.ServiceHosts)
            {
                serviceHost.Open();
            }

            Console.WriteLine("服务已启动...");
        }
        #endregion

        #region # 关闭服务——void Stop()
        /// <summary>
        /// 关闭服务
        /// </summary>
        public virtual void Stop()
        {
            foreach (var serviceHost in this.ServiceHosts)
            {
                serviceHost.Close();
            }

            Console.WriteLine("服务已关闭...");
        }  
        #endregion
        #endregion
    }
}
